﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Threading;
using System.Runtime.InteropServices;

namespace HiRM
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : System.Windows.Application
    {
        private static Mutex _mutex;
        private MainWindow _mainWindow;
        private static DateTime _startTime;

        protected override void OnStartup(StartupEventArgs e)
        {
            if (IsSingleInstance())
            {
                _startTime = DateTime.Now;
                base.OnStartup(e);
                _mainWindow = new MainWindow();
                _mainWindow.Show();
                CreateActivationEvent();
            }
            else
            {
                ActivateExistingInstance();
                Environment.Exit(0);
            }
        }

        private bool IsSingleInstance()
        {
            _mutex = new Mutex(true, "HiRM_SingleInstance_Mutex");
            return _mutex.WaitOne(0, false);
        }

        private void ActivateExistingInstance()
        {
            EventWaitHandle.TryOpenExisting("HiRM_ActivateEvent", out var eventHandle);
            eventHandle?.Set();
        }

        public void CreateActivationEvent()
        {
            var thread = new Thread(() =>
            {
                while (true)
                {
                    var activationEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "HiRM_ActivateEvent");
                    activationEvent.WaitOne();
                    Dispatcher.Invoke(() =>
                    {
                        if (_mainWindow != null)
                        {
                            _mainWindow.Show();
                            _mainWindow.WindowState = WindowState.Normal;
                            _mainWindow.Activate();
                        }
                    });
                    activationEvent.Close();
                }
            });
            thread.IsBackground = true;
            thread.Start();
        }

        public void ShowWindow()
        {
            if (_mainWindow != null)
            {
                _mainWindow.Show();
                _mainWindow.WindowState = WindowState.Normal;
                _mainWindow.Activate();
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
            }
            base.OnExit(e);
        }
    }
}
